package com.anji.plus.gaea.push.type.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaUniformMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedisBetterConfigImpl;
import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.constant.GaeaKeyConstant;
import com.anji.plus.gaea.push.support.AbstractPushSender;
import com.anji.plus.gaea.push.type.base.BasePushDetails;
import com.anji.plus.gaea.push.type.param.PushParamVO;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.redis.RedisTemplateWxRedisOps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Arrays;

/**
 * 微信小程序发送
 *
 * @author lr
 * @since 2021-02-07
 */
public class GaeaWeChatMiniAppTemplate extends AbstractPushSender<WeChatMiniAppPushDetails> {

    private Logger logger = LoggerFactory.getLogger(GaeaWeChatMiniAppTemplate.class);

    @Autowired
    private GaeaPushWeChatMiniAppProperties pushWeChatMiniappProperties;

    private final WxMaService wxMaService = new WxMaServiceImpl();

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 发送消息,由子类实现
     *
     * @param message
     * @return
     * @throws Exception
     */
    @Override
    public ResponseBean doSend(WeChatMiniAppPushDetails message) {

        Arrays.stream(message.getToUser().split(GaeaConstant.SPLIT)).forEach(user -> {
            try {
                if (StringUtils.isBlank(user)) {
                    return;
                }
                if (message.isMpTemplateMsg()) {
                    //公众号消息
                    getWxMaService(message.getAppid(), message.getSecret()).getMsgService().sendUniformMsg(WxMaUniformMessage.builder()
                                    .isMpTemplateMsg(true)
                                    .appid(message.getMpAppid())
                                    .templateId(message.getTemplateId())
                                    .toUser(message.getToUser())
                                    .miniProgram(message.buildMiniProgram(message.getAppid(), message.getPage()))
                                    .data(message.convertMpData())
                            .build()
                    );
                }else {
                    //小程序消息
                    getWxMaService(message.getAppid(), message.getSecret()).getSubscribeService()
                            .sendSubscribeMsg(WxMaSubscribeMessage.builder()
                                    .templateId(message.getTemplateId())
                                    .toUser(user)
                                    .page(message.getPage())
                                    .data(message.convertMiniAppData())
                                    .lang(message.getLang())
                                    .miniprogramState(message.getMiniprogramState())
                                    .build());
                }
            } catch (WxErrorException e) {
                logger.info("push miniapp error:{}", e.getMessage());
                throw new RuntimeException(e);
            }
        });
        return ResponseBean.builder().build();
    }

    /**
     * 获取wx实例,系统配置
     *
     * @return
     */
    public WxMaService getWxMaService() {
        return getWxMaService(null, null);
    }

    /**
     * 获取wx实例，自定义实例
     *
     * @return
     */
    public WxMaService getWxMaService(String appid, String secret) {
        //未传，取系统配置的
        if (StringUtils.isBlank(appid) || StringUtils.isBlank(secret)) {
            appid = pushWeChatMiniappProperties.getAppid();
            secret = pushWeChatMiniappProperties.getSecret();
            if (StringUtils.isBlank(appid) || StringUtils.isBlank(secret)) {
                logger.info("未配置微信小程序的appid或secret...");
            }
        }
        boolean switchover = false;
        try {
            switchover = wxMaService.switchover(appid);
        } catch (NullPointerException e) {
            //第一次初始化不存在会报异常
            logger.info("wx not exist config...");
        }

        //判断是否存在mpId
        if (!switchover) {
            //add config
            WxMaRedisBetterConfigImpl wxMaConfig = new WxMaRedisBetterConfigImpl(new RedisTemplateWxRedisOps(redisTemplate), GaeaKeyConstant.WX_PERFIX);
            wxMaConfig.setAppid(appid);
            wxMaConfig.setSecret(secret);
            wxMaService.addConfig(appid, wxMaConfig);
            logger.info("add wx config:{}", wxMaConfig);
        }
        return wxMaService;
    }

    @Override
    public BasePushDetails convert(PushParamVO pushParamVO) {
        String templateInfo = pushParamVO.getTemplateInfo();
        WeChatMiniAppPushDetails details = JSONObject.parseObject(templateInfo, WeChatMiniAppPushDetails.class);
        details.setToUser(pushParamVO.getTo());
        if (null != pushParamVO.getParamMap()) {
            details.setData(pushParamVO.getParamMap());
        }
        return details;
    }
}

